package com.tianzehua.netty.heartbeatexample;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;


/**
 * heartbeat server handler{@link ChannelInboundHandlerAdapter}
 * @author  tianzehua
 * @date  2019/03/10
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    /* ChannelInboundHandlerAdapter 是 SimpleChannelInboundHandler 的父类，该类中有一个方法 userEventTriggered,
    * 该方法的作用就是将事件触发后，传递给下一个方法 */

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
          IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

          String eventType = null;
          switch (idleStateEvent.state()){
              case READER_IDLE:
                  eventType = "读空闲";
                  break;
              case WRITER_IDLE:
                  eventType = "写空闲";
                  break;
              case ALL_IDLE:
                  eventType = "读写空闲";
                  break;
              default:
          }

          System.out.println(ctx.channel().remoteAddress() + "超时事件：" + eventType);

          ctx.channel().close();
        }
        super.userEventTriggered(ctx, evt);
    }
}
